package br.sed.theenemy.presentation.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

import br.sed.theenemy.business.exception.DBException;
import br.sed.theenemy.business.exception.InvalidUniqueBeanException;
import br.sed.theenemy.business.exception.InvalidUserException;
import br.sed.theenemy.business.services.Services;
import br.sed.theenemy.model.bean.User;
import br.sed.theenemy.presentation.EnemyErrorConstants;
import br.sed.theenemy.presentation.UserSession;
import br.sed.theenemy.presentation.action.json.JSONBaseAction;
import br.sed.theenemy.presentation.action.json.exception.ExpectedException;
import br.sed.theenemy.presentation.form.RegisterContactForm;

/**
 * 
 * @author JulioCB
 * @email jcbjulio@gmail.com
 * 
 */
public class RegisterContactAction extends JSONBaseAction {

	protected Object executeJSON(final ActionMapping mapping,final HttpServletRequest request, final ActionForm form) throws ExpectedException{
		Services services = Services.getInstance();
		
		RegisterContactForm registerContact = (RegisterContactForm) form;
		
		if(registerContact.validate(mapping, request).size()!=0){
			throw new ExpectedException(EnemyErrorConstants.MISSING_PARAM);
		}
		
		Long targetId = registerContact.getContactId();
		
		final UserSession session = new UserSession(request, false);
        final User user = session.getLoggedUser();
        
        if (user == null) {
            // User not logged in
        	throw new ExpectedException(EnemyErrorConstants.USER_NOT_LOGGED);
        } 
		
        try {
			services.createContact(user.getId(), targetId);
		} catch (DBException e) {
			throw new ExpectedException(EnemyErrorConstants.DB_EXCEPTION);
		} catch (InvalidUniqueBeanException e) {
			throw new ExpectedException(EnemyErrorConstants.INCORRECT_PARAM);
		} catch (InvalidUserException e) {
            // TODO 
        }

		return null;
	}
}
